import time
from datetime import datetime, timedelta, date
from django.template import loader, RequestContext
from django.shortcuts import render_to_response
from django.views.generic import date_based
from simplestats.models import PageView
from django.http import Http404

def day_detail(request, year, month, day):
    try:
        year = int(year)
        month = int(month)
        day = int(day)
    except:
        raise Http404
    dt = datetime(year, month=month, day=day)
    data = PageView.objects.by_hour(dt)
    context = {
        'data': data,
        'datetime' : dt,
    }
    return render_to_response(
        "simplestats/day.html",
        context,
        context_instance = RequestContext(request)
    )

def month_detail(request, year, month):
    try:
        year = int(year)
        month = int(month)
    except:
        raise Http404
    dt = datetime(year, month=month, day=1)
    data = PageView.objects.by_day(dt)
    context = {
        'data': data,
        'datetime': dt,
    }
    return render_to_response(
        "simplestats/month.html",
        context,
        context_instance = RequestContext(request)
    )

def custom_archive_month(request, year, month, queryset, date_field,
        month_format='%b', template_name=None, template_loader=loader,
        extra_context=None, allow_empty=False, context_processors=None,
        template_object_name='date', mimetype=None, allow_future=False):
    """
    Generic monthly archive view.

    Templates: ``<app_label>/<model_name>_archive_month.html``
    Context:
        month:
            (date) this month
        next_month:
            (date) the first day of the next month, or None if the next month is in the future
        previous_month:
            (date) the first day of the previous month
        date_list:
            list of days with published data in the given month
    """
    if extra_context is None: extra_context = {}
    try:
        obj_date = date(*time.strptime(year+month, '%Y'+month_format)[:3])
    except ValueError:
        raise Http404

    model = queryset.model
    now = datetime.now()

    # Calculate first and last day of month, for use in a date-range lookup.
    first_day = obj_date.replace(day=1)
    if first_day.month == 12:
        last_day = first_day.replace(year=first_day.year + 1, month=1)
    else:
        last_day = first_day.replace(month=first_day.month + 1)
    lookup_kwargs = {'%s__range' % date_field: (first_day, last_day)}

    # Only bother to check current date if the month isn't in the past and future objects are requested.
    if last_day >= now.date() and not allow_future:
        lookup_kwargs['%s__lte' % date_field] = now
    date_list = queryset.filter(**lookup_kwargs).dates(date_field, 'day')
    if not date_list and not allow_empty:
        raise Http404

    # Calculate the next month, if applicable.
    if allow_future:
        next_month = last_day + timedelta(days=1)
    elif last_day < obj_date.today():
        next_month = last_day + timedelta(days=1)
    else:
        next_month = None

    if not template_name:
        template_name = "%s/%s_archive_month.html" % (model._meta.app_label, model._meta.object_name.lower())
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    extra_context.update({
        '%s_list' % template_object_name: date_list,
        'month': obj_date,
        'next_month': next_month,
        'previous_month': first_day - timedelta(days=1),
    })
    return render_to_response(template_name,
        extra_context,
        mimetype=mimetype,
        context_instance = RequestContext(request, {}, context_processors)
    )

def year_detail(request, year):
    try:
        year = int(year)
    except:
        raise Http404
    dt = datetime(year, month=1, day=1)
    data = PageView.objects.by_month(dt)
    context = {
        'data': data,
        'datetime': dt,
    }
    return render_to_response(
        "simplestats/year.html",
        context,
        context_instance = RequestContext(request)
    )

def index(request):
    dt = datetime.now()
    data = PageView.objects.by_hour(dt)
    context = {
        'data': data,
        'datetime': dt,
    }
    return render_to_response(
        "simplestats/index.html",
        context,
        context_instance = RequestContext(request)
    )